package com.ocean.everyday.d007_decodethemessage;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * https://leetcode.cn/problems/decode-the-message/
 * 解密消息
 *
 * @author linmiaolai@sanyygp.com<br>
 * @version 1.0<br>
 * @date 2023/02/01 <br>
 */
public class DecodeTheMessage {

    public static void main(String[] args) {
        DecodeTheMessage decodeTheMessage = new DecodeTheMessage();
        System.out.println(decodeTheMessage.decodeMessage("the quick brown fox jumps over the lazy dog", "vkbs bs t suepuv"));
        System.out.println(decodeTheMessage.decodeMessage("eljuxhpwnyrdgtqkviszcfmabo", "zwx hnfx lqantp mnoeius ycgk vcnjrdb"));

    }

    /**
     * 输入：key = "the quick brown fox jumps over the lazy dog", message = "vkbs bs t suepuv"
     * 输出："this is a secret"
     * <p>
     * 输入：key = "eljuxhpwnyrdgtqkviszcfmabo", message = "zwx hnfx lqantp mnoeius ycgk vcnjrdb"
     * 输出："the five boxing wizards jump quickly"
     *
     * @param key
     * @param message
     * @return
     */
    public String decodeMessage(String key, String message) {
        Character cur = 'a';
        // 字符对照表
        Map<Character, Character> map = new HashMap<>();
        int length = key.length();
        for (int i = 0; i < length; i++) {
            char c = key.charAt(i);
            if (c == ' ' || map.containsKey(c)) {
                continue;
            }
            map.put(c, cur);
            cur++;
        }
        // 有了对照表 开始解密
        StringBuilder builder = new StringBuilder();
        int n = message.length();
        for (int j = 0; j < n; j++) {
            char c = message.charAt(j);
            if (c != ' ') {
                // 从表中获取
                c = map.get(c);
            }
            builder.append(c);
        }
        return builder.toString();
    }


    public String decodeMessage2(String key, String message) {
        char[] keyMap = new char[26];
        Arrays.fill(keyMap, '0');
        int idx = 'a';
        for (char keyChar : key.toCharArray()) {
            int charIdx = keyChar - 'a';
            if (charIdx < 0 || charIdx > 25) continue;
            if (keyMap[charIdx] == '0') {
                keyMap[charIdx] = (char) idx;
                idx++;
            }
        }
        char[] messageCharArr = message.toCharArray();
        for (int i = 0; i < messageCharArr.length; i++) {
            int mapIdx = messageCharArr[i] - 'a';
            if (mapIdx < 0 || mapIdx > 25) continue;
            messageCharArr[i] = keyMap[mapIdx];
        }
        return new String(messageCharArr);
    }

}
